/**
 * 
 */
package info.niwota.js;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;


/**
 * @author qiangli
 * 
 */
public class Processor {
	public static boolean compress = true;

	public static boolean gzip = true;

	public static Compressor jsCompressor = new YUIJsCompressor();

	//public static Compressor cssCompressor = new YUICssCompressor();
	
	private Processor() {
	}
	
	public static void process(String mimeType, String acceptEncoding, String in, OutputStream out) throws Exception {
//		if (mimeType == null) {
//			mimeType = "application/octet-stream";
//		}
//		
//		final boolean supportGzip = supportGzip(acceptEncoding);
//		
//		if (compress && mimeType.equals("text/javascript")) {
//			OutputStream os = (supportGzip ? out : new GZIPOutputStream(new BufferedOutputStream(out)));
//			//jsCompressor.compress(in, os);
//			return;
//		}
		
//		if (compress && mimeType.equals("text/css")) {
//			OutputStream os = (supportGzip ? out : new GZIPOutputStream(new BufferedOutputStream(out)));
//			cssCompressor.compress(in, os);
//			return;
//		}
	}

	public static boolean supportGzip(String acceptEncoding) {
		boolean b = false;
		if (acceptEncoding != null
				&& acceptEncoding.toLowerCase().indexOf("gzip") != -1) {
			b = true;
		}
		return b;
	}

	public static void gzip(InputStream in, OutputStream out) throws Exception {
		BufferedInputStream bis = null;
		GZIPOutputStream gos = null;
		bis = new BufferedInputStream(in);
		gos = new GZIPOutputStream(new BufferedOutputStream(out));
		byte[] buf = new byte[4096];
		int nread = -1;
		while ((nread = bis.read(buf)) != -1) {
			gos.write(buf, 0, nread);
		}
		gos.flush();
	}

//	private static void close(Closeable os) {
//		try {
//			os.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
}
